#import scanf
import parse
import fire
import time
import datetime
import os
import random
from math import sin

# 输出log，便于调试
import logging


def update_data_dict_gen(t=None,mode='sin'):
    """假造一些数据，返回字典格式
    """
    now_ts = time.time() if t is None else t # 默认当前时间
    update_data_dict = {}
    
    # 时间处理
    now_datetime = datetime.datetime.fromtimestamp(now_ts)
    deltatime_since_year = now_datetime - datetime.datetime(year=now_datetime.year,month=1,day=1)
    seconds_since_midnight = deltatime_since_year.total_seconds() - deltatime_since_year.days*24*3600

    update_data_dict['YEAR'] = now_datetime.year
    update_data_dict['DAY'] = deltatime_since_year.days
    update_data_dict['SecAftMid'] = seconds_since_midnight

    if mode == 'sin':
        # 正弦变化的数据
        period = 100 # s
        shift = 10 # s
        update_data_dict['Sulf'] = sin((now_ts+shift*0)/period)
        update_data_dict['Nitr']=  sin((now_ts+shift*1)/period)
        update_data_dict['Org_Low']= sin((now_ts+shift*2)/period)
        update_data_dict['Cl']= sin((now_ts+shift*3)/period)
    elif mode == 'random':
        max = 1.0
        min = 0.0
        update_data_dict['Sulf'] = random.random()*(max-min)+min
        update_data_dict['Nitr']=  random.random()*(max-min)+min
        update_data_dict['Org_Low']= random.random()*(max-min)+min
        update_data_dict['Cl']= random.random()*(max-min)+min
    else:
        raise RuntimeError(f'mode={mode}, it must be "sin" or "random"')
    return update_data_dict


def main(output_filename= None,
        delay_time = 0.95,
        test_mode=False,
        max_time_hours = 24,
        mode='sin',
        log_level = 'INFO'):
    """假造一些输出到log文件，模拟实际设备
    """
    # 初始化
    logging.basicConfig(level = getattr(logging,log_level.upper(),logging.INFO)) # 默认info
    file_base_name = os.path.basename(__file__)
    logger = logging.getLogger(file_base_name)

    # 分隔符
    sep = '\t'
    # 列名
    col_names = 'YEAR	DAY	SecAftMid	TofType	IonType	MS_AB	PToF_AB	Flow	Sulf	Nitr	Org_Low	Cl	Imz_43	Imz_44	Imz_57	usmz_01	Iusmz_01	usmz_02	Iusmz_02	usmz_03	Iusmz_03	usmz_04	Iusmz_04	usmz_05	Iusmz_05	usmz_06	Iusmz_06	usmz_07	Iusmz_07	usmz_08	Iusmz_08	usmz_09	Iusmz_09	usmz_10	Iusmz_10	aiV0	aiV1	aiV2	aiV3	aiV4	aiV5	aiV6	aiV7	'.split('\t')[:-1]
    
    # 格式
    write_formats = ['04d','03d','8.2f','1d','1d',	'8.2f','08d']+['5.3f']*8+['04d','5.3f']*10 +['5.3f']*8
    read_formats = [format[-1] for format in write_formats]

    # data types
    data_types = dict(zip(col_names, read_formats))
    
    # 默认值，为保持完整性
    defaults_str = '2021	019	31800.59	1	0	33201.70	00000000	1.318	1.529	3.158	3.206	0.408	0.184	0.487	0.059	0030	1.198	0041	0.756	0046	0.890	0048	0.209	0055	0.081	0064	0.275	0069	0.043	0077	0.020	0091	0.027	0202	0.011	0.772	4.411	4.021	1.027	0.967	0.966	0.927	0.866	'

    # 需要上传或生成的列
    selected_cols = 'Sulf,Nitr,Org_Low,Cl'.split(',')

    # 第一行
    header = sep.join(col_names)+sep
    logger.info(header)

    # 生成格式化字符串
    line_write_formatter=sep.join([f'{{{col_name}:{format}}}' for col_name,format in zip(col_names,write_formats)])+sep
    logger.info(line_write_formatter)

    line_read_formatter=sep.join([f'{{{col_name}:{format}}}' for col_name,format in zip(col_names,read_formats)])+sep
    logger.info(line_read_formatter)

    # 简单测试
    parse_result = parse.parse(line_read_formatter,defaults_str)
    logger.info(parse_result)

    # 默认值
    data_dict_defaults = parse_result.named 

    # example data
    # raw_data_example_filename = r"raw_data\课题3\AMS\AMS_TimeTrace_033270.txt"
    
    # 输出文件名
    output_filename = output_filename if output_filename is not None else (file_base_name+r".test.log")
    with open(output_filename,'w+',encoding='utf-8') as OF:
        if test_mode: OF = None
        #header
        print(header,file=OF)
        #lines
        start_time = time.time()
        while(time.time()<start_time + max_time_hours*24*3600): # max hours
            data_dict = data_dict_defaults
            update_data_dict = update_data_dict_gen(mode=mode)
            data_dict.update(update_data_dict)
            line = line_write_formatter.format(**data_dict)
            print(line,file=OF,flush=True)
            time.sleep(delay_time)

if __name__ == "__main__":
    fire.Fire(main) # 利用fire命令行化